package com.newlink.building

import android.annotation.SuppressLint
import android.content.Context
import com.newlink.building.common_base.base.BaseApplication
import com.newlink.building.common_base.utils.logDebug
import com.newlink.building.core.Module_Phone_CoreContext
import com.newlink.building.core.Module_Phone_CorePreferences
import com.newlink.building.manager.Module_Phone_VoipController
import org.linphone.core.Factory
import org.linphone.core.LogCollectionState
import org.linphone.core.LogLevel
import org.linphone.core.tools.Log
import kotlin.properties.Delegates

/**
 * Created by xiaodong on 2022/8/8.
 */
open class NL_App : BaseApplication() {

    override fun onCreate() {
        super.onCreate()
        logDebug<NL_App>("onCreate")
        context = applicationContext
        createConfig(applicationContext)
        Module_Phone_VoipController.create(context)
    }

    companion object {
        var context: Context by Delegates.notNull()
            private set

        /**
         * core相关配置
         */
        @SuppressLint("StaticFieldLeak")
        lateinit var corePreferences: Module_Phone_CorePreferences

        /**
         * 对core的封装,通过coreContext.core获取
         */
        @SuppressLint("StaticFieldLeak")
        lateinit var coreContext: Module_Phone_CoreContext

        /**
         *初始化linhone相关配置
         */
        private fun createConfig(context: Context) {
            if (Companion::corePreferences.isInitialized) {
                return
            }

            Factory.instance().setLogCollectionPath(context.filesDir.absolutePath)
            Factory.instance().enableLogCollection(LogCollectionState.Enabled)

            corePreferences = Module_Phone_CorePreferences(context)
            corePreferences.copyAssetsFromPackage()

            if (corePreferences.vfsEnabled) {
                Module_Phone_CoreContext.activateVFS()
            }

            val config = Factory.instance().createConfigWithFactory(
                corePreferences.configPath,
                corePreferences.factoryConfigPath
            )
            corePreferences.config = config

            val appName = context.getString(R.string.app_name_smart)
            Factory.instance().setLoggerDomain(appName)
            Factory.instance().enableLogcatLogs(corePreferences.logcatLogsOutput)
//            if (corePreferences.debugLogs) {
            Factory.instance().loggingService.setLogLevel(LogLevel.Message)
//            }

            Log.i("[Application] Core config & preferences created")
            ensureCoreExists(context)
        }

        fun ensureCoreExists(context: Context, pushReceived: Boolean = false) {
            if (Companion::coreContext.isInitialized && !coreContext.stopped) {
                Log.d("[Application] Skipping Core creation (push received? $pushReceived)")
                return
            }

            Log.i("[Application] Core context is being created ${if (pushReceived) "from push" else ""}")
            coreContext = Module_Phone_CoreContext(context, corePreferences.config)
            coreContext.start()
            corePreferences.copyStaticPicure()
            corePreferences.acceptEarlyMedia = true
            corePreferences.globalSupportEarlyMedia = true
            coreContext.core.ringDuringIncomingEarlyMedia = false
        }

        fun contextExists(): Boolean {
            return Companion::coreContext.isInitialized
        }

        fun exitCoreService() {
            coreContext.stop()
        }
    }
}